<?php
// --
function redirect($url){
    header("location: ".$url);
    exit();
}

// ------------------------------------------------------------
// --- [ Retrieve PHP version ] -------------------------------
// ------------------------------------------------------------

/**
 * php_VersionCheck retrieve current PHP version
 *
 * @param string $mini - min php version to check with current
 * @return int{0,1}
 */
function getsafeccnumber($n = false,$show = 4){
    if($n == false or $show < 0){return false;}
    $n_len = strlen($n);
    $unhide = substr($n,-$show);
    $r = ereg_replace("([0-9])",'*',substr($n,0,($n_len-$show))); #hide all numbers
    
    $safe = $r.$unhide;
    return $safe;
}


function php_VersionCheck($mini)
{
    $dummy=phpversion();
    sscanf($dummy,"%d.%d.%d%s",&$v1,&$v2,&$v3,&$v4);
    sscanf($mini,"%d.%d.%d%s",&$m1,&$m2,&$m3,&$m4);

    if($v1>$m1)        return(1);
    elseif($v1<$m1)    return(0);
    if($v2>$m2)        return(1);
    elseif($v2<$m2)    return(0);
    if($v3>$m3)        return(1);
    elseif($v3<$m3)    return(0);
    if((!$v4)&&(!$m4)) return(1);
    if(($v4)&&(!$m4)) {
        $dummy=strpos($v4,"pl");
        if(is_integer($dummy))
        {
            return 1;
        }
        return 0;
    }
    elseif((!$v4)&&($m4)) {
        $dummy=strpos($m4,"rc");
        if(is_integer($dummy))
        {
            return 1;
        }
        return 0;
    }
    return 0;
}

// ------------------------------------------------------------
// --- [ Debug function ] -------------------------------------
// ------------------------------------------------------------

/**
 * Show debug info of the arrays, objects, variables
 *
 * @param mixed $variable - variable to show
 * @param string $comments - comments for the debug box
 */
function debug($variable, $comments="")
{
    echo "<pre style=\"border:1px solid #000000; background-color: #CDCDCD;\">".("" == $comments ? "" : "<b>$comments</b>\n");
    print_r($variable);
    echo "\n</pre>\n<br />\n";
}




// ----------------------------------------------------------
// --- [ Safe String Operation ] ----------------------------
// ----------------------------------------------------------

function dbSafeString($str)
{
    return addslashes($str);
}

/**
 * Convert safe safe string to normal string
 *
 * @param string $str - source string
 * @return string
 */
function db2str($str)
{
    return stripslashes($str);
}

/**
 * Create safe for database string
 *
 * @param string $str - source string
 * @return string
 */
function str2db($str)
{
    return addslashes(trim($str));
}

/**
 * Split string into array and trim each item
 *
 * @param string $sep - separator
 * @param string $str - string to process
 * @return array
 */
function strSplit($sep, $str)
{
    $res = split($sep, $str);
    $result = array();
    foreach($res as $v)
    {
        $result[] = trim($v);
    }
    return $result;
}


/**
 * Make all strings in the multi-dimentional array to safe strings
 *
 * @param array $arr - source array to process
 * @param integer $deep - internal variable (do not modify!)
 * @return array with safe strings
 */
function ArrayStr2db(&$arr, $deep = 0 )
{
    if(is_array($arr) && count($arr))
    {
        foreach($arr as $k => $v)
        {
            if(is_array($v) && count($v))
            {
                ArrayStr2db($v, $deep+1);
            }
            if(is_string($v))
            {
                $arr[$k] = str2db($v);
            }
            else
            {
                $arr[$k] = $v;
            }
        } // end foreach
    }
    return $arr;
}

/**
 * Make all safe strings in the multi-dimentional array into unsafe strings
 *
 * @param array $arr - source array to process
 * @param integer $deep - internal variable (do not modify!)
 * @return array with unsafe strings
 */
function ArrayDb2Str(&$arr, $deep = 0 )
{
    if(is_array($arr) && count($arr))
    {
        foreach($arr as $k => $v)
        {
            if(is_array($v) && count($v))
            {
                ArrayDb2Str($v, $deep+1);
            }
            if(is_string($v))
            {
                $arr[$k] = db2str($v);
            }
            else
            {
                $arr[$k] = $v;
            }
        } // end foreach
    }
    return $arr;
}



/**
 * Reorganize indexes in the array. For ex
 *   0 => Abc           0 => Abc
 *   2 => Dfr   ====>   1 => Dfr
 *   5 => Zde           2 => Zde
 *
 * @param array $arrIn input array to be processing
 * @return array
 */
function ArrayReIndex($arrIn)
{
    $arrout = array();
    foreach($arrIn as $v)
    {
        $arrout[] = $v;
    }
    return $arrout;
}




// ----------------------------------------------------------
// --- [ Generate Password ] --------------------------------
// ----------------------------------------------------------

/**
 * Function returns generated password from 4 to 15 characters length
 * includes [a-zA-Z0-9_] symbols
 *
 * @return string passord
 */
function genPassword()
{
    $min=4;     // minimum length of password
    $max=8;     // maximum length of password
    $pwd="";    // to store generated password
    for($i=0;$i<rand($min,$max);$i++)
    {
        $num=rand(48,122);
        if(($num > 97 && $num < 122))
        {
            $pwd.=chr($num);
        }
        else if(($num > 65 && $num < 90))
        {
            $pwd.=chr($num);
        }
        else if(($num >48 && $num < 57))
        {
            $pwd.=chr($num);
        }
        else if($num==95)
        {
            $pwd.=chr($num);
        }
        else
        {
            $i--;
        }
    } // end for
    return $pwd;
}



// ------------------------------------------------------------
// -- Short-text aliases
// ------------------------------------------------------------

$php_min_ver = "4.2.0";

global $_P, $_G, $_S, $_C;

if(!php_VersionCheck($php_min_ver))
{
    $_P = &$HTTP_POST_VARS;
    $_G = &$HTTP_GET_VARS;
    $_S = &$HTTP_SESSION_VARS;
    $_C = &$HTTP_COOKIE_VARS;

    function G($var) { global $HTTP_GET_VARS; return $HTTP_GET_VARS[$var]; }
    function P($var) { global $HTTP_POST_VARS; return $HTTP_POST_VARS[$var]; }
    function S($var) { global $HTTP_SESSION_VARS; return $HTTP_SESSION_VARS[$var]; }
    function C($var) { global $HTTP_COOKIE_VARS; return $HTTP_COOKIE_VARS[$var]; }

    function isG($var) { global $HTTP_GET_VARS; return isset($HTTP_GET_VARS[$var]); }
    function isP($var) { global $HTTP_POST_VARS; return isset($HTTP_POST_VARS[$var]); }
    function isS($var) { global $HTTP_SESSION_VARS; return isset($HTTP_SESSION_VARS[$var]); }
    function isC($var) { global $HTTP_COOKIE_VARS; return isset($HTTP_COOKIE_VARS[$var]); }

    function unS($var) { global $HTTP_SESSION_VARS; if(isS($var)) unset($HTTP_SESSION_VARS[$var]); }
}
else
{
    $_P = &$_POST;
    $_G = &$_GET;
    $_S = &$_SESSION;
    $_C = &$_COOKIE;

    function G($var) { return $_GET[$var]; }
    function P($var) { return $_POST[$var]; }
    function S($var) { return $_SESSION[$var]; }
    function C($var) { return $_COOKIE[$var]; }

    function isG($var) { return isset($_GET[$var]); }
    function isP($var) { return isset($_POST[$var]); }
    function isS($var) { return isset($_SESSION[$var]); }
    function isC($var) { return isset($_COOKIE[$var]); }

    function unS($var) { if(isset($_SESSION[$var])) unset($_SESSION[$var]); }
}

/**
 * short name of isset($var) and !empty($var)
 *   0 => Abc           0 => Abc
 *   2 => Dfr   ====>   1 => Dfr
 *   5 => Zde           2 => Zde
 *
 * @param varriable $var
 * @return isset($var) and !empty($var)
 */
function isne($var)
{
    if(isset($var) and !empty($var) )
    {
        return true;
    }else
    {
        return false;
    }
}
/**
 * copy file $_FILES[$FName]['tmp_name'] to new path : $copy_to
 *
 * @param varriable $FName , $copy_to
 * @return $copy_to if it's all ok
 */

function uploadFile($FName,$copy_to,$setp){
    if (!isset($setp))
    $setp = 0;
    
    $rwpermission = '777';
    $filepath = $core->config["file_root"].$copy_to;
    $pxx = null;
    $core = getCoreInstance();
    if(is_uploaded_file($_FILES[$FName]['tmp_name'])) {
        
        if(!copy($_FILES[$FName]['tmp_name'], $core->config["file_root"].$copy_to)) {
        if($setp == 1) {
            if(!chmod($core->config["file_root"].$copy_to ,$rwpermission))  {
                
                echo("Cannot set file permission ".$rwpermission." to ".$core->config["file_root"].$copy_to);
                                                    }
            else {echo("$filepath set 777");}
                       }
            
            die("Can't copy file ".$_FILES[$FName]['tmp_name']." to the '{$core->config["file_root"]}{$copy_to}' !");
        }else {
            $pxx = $core->config["file_root"].$copy_to ;
        }
    }
    return $pxx;
}

// ---  [ Create full tree heading] ----------------------------
function getAllHistory($pid, $rstr = "", &$arr)
{
    $core = getCoreInstance();
    $db = $core->getProperty("db");
    $q = "select * from catalog where is_category='Y' and parent_id=".($pid > 0 ? "{$pid}" : "0");
    $ctg = Arraydb2str($db->getAll($q));

     if(count($ctg))
    {
        $arr[] = array("id" => $pid, "title" => $rstr == ""?"Root":$rstr);
        foreach ($ctg as $v)
        {
            getAllHistory($v["catalog_id"], $rstr=="" ? $v["title"] : $rstr . ": ".$v["title"], $arr);
        }
    }
    else
    {
        $arr[] = array("id" => $pid, "title" => $rstr);
    }

}

/**
 * Returns html <img src=...> code with image if all ok
 *
 * @param 'uploads/imp1_1_1.jpg' $db_path
 * @param 'image alter text' 
 * @param  $core
 * @return array (status,result)
 */
function my_getimage($db_path,$alt,$core){
        $fileroot = $core->config["file_root"];
        $httproot = $core->config["http_root"];
        $img = $db_path;
        
        if('' != $img and 'img/no_image' != $img 
        and file_exists($fileroot.'/inventory/'.$img)){
           $v_img = $httproot.'inventory/'.$img;
           $v_img_html = $v_img = "<img src='".$v_img."' border='0' alt='{$alt}'>";
           $s = 'ok';

        }
        elseif ('' == $img or 'img/no_image.jpg' == $img or 
        !file_exists($fileroot.'inventory/'.$img)) {
           $v_img_html = $v_img = "<img src='".$httproot."img/no_image.jpg' border='0' alt='{$data[vendor_name]} Logo'>";
           $s = 'empty';
           
        }
        else{
           $v_img_html = 'Corrupt image data';
           $s = 'error'; 
        }
        
        $r = array('Status' => $s, 'result' => $v_img_html);
        return $r;
    }

?>